import { defineStore } from 'pinia';
import axios from 'axios';

interface SystemConfig {
  id: number;
  configKey: string;
  configValue: string;
  description: string;
}

export const useSystemConfigStore = defineStore('systemConfig', {
  state: () => ({
    configs: new Map<string, SystemConfig>(),
    loading: false,
    error: null as string | null,
  }),
  
  getters: {
    getConfig: (state) => (key: string) => {
      return state.configs.get(key);
    },
    
    waterfallColumns: (state): number => {
      const config = state.configs.get('waterfall_columns');
      return config ? parseInt(config.configValue) || 3 : 3; // 默认3列
    }
  },
  
  actions: {
    async getConfigByKey(key: string) {
      if (this.configs.has(key)) {
        return this.configs.get(key);
      }
      
      try {
        this.loading = true;
        this.error = null;
        
        const response = await axios.get(`/api/config/${key}`);
        if (response.status === 200) {
          this.configs.set(key, response.data);
          return response.data;
        } else {
          throw new Error('Failed to fetch config');
        }
      } catch (error) {
        console.error(`Failed to get config for key ${key}:`, error);
        this.error = `Failed to get config for key ${key}`;
        return null;
      } finally {
        this.loading = false;
      }
    },
    
    async updateConfig(key: string, value: string) {
      try {
        this.loading = true;
        this.error = null;
        
        const response = await axios.post(`/api/config/${key}`, { value });
        if (response.status === 200) {
          this.configs.set(key, response.data);
          return response.data;
        } else {
          throw new Error('Failed to update config');
        }
      } catch (error) {
        console.error(`Failed to update config for key ${key}:`, error);
        this.error = `Failed to update config for key ${key}`;
        return null;
      } finally {
        this.loading = false;
      }
    },
    
    async initializeConfigs() {
      // 初始化常用配置
      await this.getConfigByKey('waterfall_columns');
    }
  }
});